﻿#include "debugLog.h"




DebugLog::DebugLog(){

#ifdef Q_OS_ANDROID
    _outRootDir = "/storage/emulated/0/Download/Log/";
#else
    _outRootDir = "./Log/";
#endif


    // 删除时间太早的Log文件
    QDir dir(_outRootDir);
    if(!dir.exists()){
        return;
    }

    // 删除日期范围
    QDateTime curDate = QDateTime::currentDateTime();
    QDateTime delDate = curDate.addDays(-_deleteTime);
    QString   endStr = delDate.toString("yyyyMMdd");
    QString   startStr = "20240101";

    // 获取路径下文件夹列表
    dir.setFilter(QDir::Dirs);
    QFileInfoList list = dir.entryInfoList();
    for(int i = 0; i < list.size(); ++ i){
        QFileInfo fileInfo = list.at(i);
        if(fileInfo.fileName() < endStr && fileInfo.fileName() > startStr){
            QDir dir(_outRootDir + fileInfo.fileName());
            dir.removeRecursively();
        }
    }
}

DebugLog& DebugLog::I(){
    static DebugLog instance;
    return instance;
}

// 控制打印时间、打印文件路径
void DebugLog::write(QString text, int type){       // type=0一般日志 1sql日志 2通信日志

    QString outdir = _outRootDir + QDateTime::currentDateTime().toString("yyyyMMdd");
    QDir dir;
    if (!dir.exists(outdir)) {
        dir.mkpath(outdir);     // 创建目录
    }

    // 文件名
    QString date= QDateTime::currentDateTime().toString("yyyyMMdd_HH");
    QString suffix = (type==0 ? "" : (type==1 ? "_SQL" : "_Comm"));

    QString outpath = outdir + "/Log_" + DEBUG_SOFTWARE_NAME + "_" + date + suffix + ".txt";


    // 打印到控制台
    if(DEBUG_ONSCREEN){
        qDebug().noquote() << "\033[32m" << ">>> " +  text << "\033[0m";
    }

    // 执行打印
    QFile file(outpath);
    bool res = file.open(QIODevice::Append);
    QString currentTime = QDateTime::currentDateTime().toString("HH-mm-ss.zzz");
    res = file.write((currentTime + "  " + text + "\n").toUtf8());
    file.close();
    return;

}
